package com.wbcs.jbsf.action;

import java.io.IOException;
import java.io.StringWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

import com.wbcs.config.component.IComponentConfigBean;
import com.wbcs.jbsf.dao.IDataModal;
import com.wbcs.jbsf.dao.JBSFDaoTemplate;
import com.wbcs.jbsf.util.JacksonMapper;
import com.wbcs.system.ReportRequest;
import com.wbcs.system.serveraction.IServerAction;
import com.wbcs.util.Consts;

public class ChangeCheckboxesAction implements IServerAction
{
    public String executeSeverAction(ReportRequest rrequest,IComponentConfigBean ccbean,List<Map<String,String>> lstData,
            Map<String,String> mCustomizedData)
    {
        // 在lstData中按照siteid进行查询，并返回查询结果为json
        JBSFDaoTemplate jdaoTemplate = new JBSFDaoTemplate(false);
        StringBuffer sql = new StringBuffer("select id, mc from t_site_info where sjid=?");
        List<Map<String,Object>> lst = new ArrayList<Map<String,Object>>();
        try{
	        for(int i=0;i<lstData.size();i++)
	        {
	            Map<String, Object> rowObjs = 
	            jdaoTemplate.<Map<String, Object>>select(sql.toString(),new IDataModal<Map<String, Object>>()
	            {
	                public Map<String,Object> loadDatas(ResultSet rs,int ccount,ResultSetMetaData rmd,Map<String,Object> dataModal)
	                        throws SQLException
	                {
	                    dataModal = new LinkedHashMap<String,Object>();
	                    while(rs.next()){
	                        dataModal.put(rs.getString(1),rs.getString(2));
	                    }
	                    return dataModal;
	                }
	            },lstData.get(i).get("siteid"));
	            lst.add(rowObjs);
	        }
        }catch(SQLException e){
        	e.printStackTrace();
        }
        
        ObjectMapper jsonMapper = JacksonMapper.getInstance();
        StringWriter sw = new StringWriter();
        JsonGenerator gen;
        try
        {
            gen=new JsonFactory().createJsonGenerator(sw);
            jsonMapper.writeValue(gen, lst); 
            gen.close();
        }catch(IOException e)
        {
            e.printStackTrace();
        }
        
        rrequest.getWResponse().setStatecode(Consts.STATECODE_NONREFRESHPAGE);
        return sw.toString().replace("\"","'");
    }

    public String executeServerAction(HttpServletRequest request,HttpServletResponse response,List<Map<String,String>> lstData)
    {
        // TODO Auto-generated method stub
        return null;
    }

}

